/**
 * 
 */
package com.zoiz.plus.extend;

import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.google.gson.Gson;
import com.zoiz.plus.renderer.Renderer;

/**
 * json render
 * 
 * @author shmiluyu
 * 
 */
public class JsonRender extends Renderer {
	private String characterEncoding;
	private Object obj;

	public JsonRender(String characterEncoding, Object obj) {
		super();
		this.characterEncoding = characterEncoding;
		this.obj = obj;
	}

	public JsonRender(Object obj) {
		super();
		this.obj = obj;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.expressme.webwind.renderer.Renderer#render(javax.servlet.ServletContext
	 * , javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void render(ServletContext context, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		StringBuilder sb = new StringBuilder(64);
		sb.append(contentType == null ? "application/json" : contentType)
				.append(";charset=")
				.append(characterEncoding == null ? "UTF-8" : characterEncoding);
		response.setContentType(sb.toString());
		PrintWriter pw = response.getWriter();
		pw.write(new Gson().toJson(obj));
		pw.flush();

	}

	public String getCharacterEncoding() {
		return characterEncoding;
	}

	public void setCharacterEncoding(String characterEncoding) {
		this.characterEncoding = characterEncoding;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

}
